//package com.lxt.cloud.config;
//
//import com.lxt.common.spring.security.SecurityUser;
//import com.lxt.common.util.IpUtils;
//import com.lxt.common.util.ResponseUtils;
//import com.lxt.oauth2.common.properties.SecurityProperties;
//import com.lxt.oauth2.provider.token.store.OauthJwtAccessTokenConverter;
//import com.lxt.oauth2.token.OauthTokenServices;
//import com.lxt.oauth2.token.TokenRefreshExecutor;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.autoconfigure.AutoConfigureAfter;
//import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.Lazy;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.http.HttpMethod;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.crypto.password.PasswordEncoder;
//import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
//import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
//import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
//import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
//import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
//import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
//import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
//import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
//import org.springframework.security.oauth2.provider.token.TokenEnhancer;
//import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
//import org.springframework.security.oauth2.provider.token.TokenStore;
//import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
//import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
//import org.springframework.util.AntPathMatcher;
//import org.springframework.web.servlet.HandlerInterceptor;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.security.KeyPair;
//import java.util.Arrays;
//import java.util.HashMap;
//import java.util.Map;
//
//@Configuration
//@EnableAuthorizationServer
//@AutoConfigureAfter(AuthorizationServerEndpointsConfigurer.class)
//public class AuthServerConfigurer extends AuthorizationServerConfigurerAdapter {
//
//	@Autowired
//	private TokenStore tokenStore;
//	@Autowired
//	private UserDetailsService userDetailsService;
//	@Autowired
//	private AuthClientDetailService authClientDetailService;
//	@Autowired
//	private AuthenticationManager authenticationManager;
//	@Autowired
//	private PasswordEncoder passwordEncoder;
//	@Autowired
//	private WebResponseExceptionTranslator webResponseExceptionTranslator;
//	@Resource
//	private JwtAccessTokenConverter serverJwtAccessTokenConverter ;
//	@Autowired
//	private SecurityProperties securityProperties;
//	@Autowired
//	private TokenRefreshExecutor tokenRefreshExecutor;
//	@Resource
//	@Lazy
//	private AuthorizationServerTokenServices authorTokenServices;
//	@Autowired
//	private RedisTemplate redisTemplate ;
//
//
//
//	private AntPathMatcher antPathMatcher = new AntPathMatcher();
//	private Logger logger = LoggerFactory.getLogger(getClass());
//
//	@Bean("keyProp")
//	public KeyProperties keyProperties() {
//		return new KeyProperties();
//	}
//
//
//	@Bean
//	public KeyPair keyPair() {
//		KeyProperties keyProperties= keyProperties();
//		KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(keyProperties.getKeyStore().getLocation(), keyProperties.getKeyStore().getSecret().toCharArray());
//		return keyStoreKeyFactory.getKeyPair(keyProperties.getKeyStore().getAlias(), keyProperties.getKeyStore().getPassword().toCharArray());
//	}
//
//
//	@Bean("serverJwtAccessTokenConverter")
//	public JwtAccessTokenConverter jwtAccessTokenConverter() {
//		JwtAccessTokenConverter accessTokenConverter =new OauthJwtAccessTokenConverter();
//		accessTokenConverter.setKeyPair(keyPair());
//		return accessTokenConverter;
//	}
//
//
//	@Bean("i18nDaoAuthenticationProvider")
//	@Lazy
//	public I18nDaoAuthenticationProvider authenticationProvider(){
//		I18nDaoAuthenticationProvider i18nDaoAuthenticationProvider=new I18nDaoAuthenticationProvider();
//		i18nDaoAuthenticationProvider.setUserDetailsService((AuthUserDetailService)userDetailsService);
//		i18nDaoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
//		return i18nDaoAuthenticationProvider;
//	}
//	@Bean("authorTokenServices")
//	@Lazy
//	public AuthorizationServerTokenServices authorTokenServices() {
//		tokenRefreshExecutor.setTokenStore(tokenStore);
//		OauthTokenServices tokenServices = new OauthTokenServices(tokenStore, tokenRefreshExecutor,redisTemplate);
//		TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
//		tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), serverJwtAccessTokenConverter));
//
//		// 非jwtConverter可注释
//		tokenServices.setTokenEnhancer(tokenEnhancerChain);
//		tokenServices.setSupportRefreshToken(true);
//		tokenServices.setReuseRefreshToken(false);
//		tokenServices.setAuthenticationManager(authenticationManager);
//		tokenServices.setClientDetailsService(authClientDetailService);
//		tokenServices.setTokenStore(tokenStore);
//		return tokenServices;
//	}
//	/**
//	 * jwt 生成token 定制化处理
//	 * 添加一些额外的用户信息到token里面
//	 *
//	 * @return TokenEnhancer
//	 */
//	@Bean
//	public TokenEnhancer tokenEnhancer() {
//		return (accessToken, authentication) -> {
//			final Map<String, Object> additionalInfo = new HashMap<>(1);
//			Object principal = authentication.getPrincipal();
//			if(principal instanceof SecurityUser){
//				SecurityUser user=(SecurityUser) principal;
//				additionalInfo.put("userId",user.getUserId());
//			}
//			((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
//			return accessToken;
//		};
//	}
//
//	@Override
//	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//		clients.withClientDetails(authClientDetailService);
//	}
//
//	@Override
//	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//
//		endpoints.authenticationManager(authenticationManager)
//				.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)  //支持GET
//				.userDetailsService(userDetailsService)
//				.tokenStore(tokenStore)
//				.tokenServices(authorTokenServices)
//				.exceptionTranslator(webResponseExceptionTranslator)
//			//该字段设置设置refresh token是否重复使用,true:reuse;false:no reuse.
//			.reuseRefreshTokens(true);
//
//		endpoints.addInterceptor(new HandlerInterceptor(){
//			@Override
//			public boolean preHandle(HttpServletRequest request,
//                                     HttpServletResponse response, Object handler)
//					throws Exception {
//				if(!antPathMatcher.match("/**/oauth/token",request.getRequestURI())){
//					return true;
//				}
//				String grantType=request.getParameter("grant_type");
//				if(!"password".equals(grantType)){
//					return true;
//				}
//
////				String remoteAddr = request.getRemoteAddr();
//				String remoteAddr=IpUtils.getIpAdrress(request);
//				if(logger.isDebugEnabled()){
//					logger.debug("remote request from browser, remote addr:{}.", remoteAddr);
//				}
////				boolean isBrowser=false;
////				if (request.getHeader("User-Agent").startsWith("Mozilla")) {
////				    logger.debug("remote request from browser, remote addr:{}.", remoteAddr);
////				    isBrowser=true;
////				}
////
////				if(!isBrowser) {
////					return true;
////				}
//				if(securityProperties.getCode().isEnable()) {
//					String authUuid = request.getParameter("auth_uuid");
//					String authCode = request.getParameter("captcha");
//					if (authUuid == null || authCode == null || authUuid.isEmpty() || authCode.isEmpty()) {
//						errorReturn(response, "请输入验证码");
//						return false;
//					}
//					logger.debug(">>>authUuid=" + authUuid);
//					String authCodeInCache = "";
//					//(String)redisTemplate.opsForValue().get("img_auth_code."+authUuid);
//					if (!authCode.equalsIgnoreCase(authCodeInCache)) {
//						errorReturn(response, "验证码不匹配");
//						return false;
//					}
//				}
//				return true;
//			}
//
//			private void errorReturn(HttpServletResponse response, String errMsg) throws Exception{
////				response.setContentType("application/json; charset=UTF-8");
////				response.getWriter().println("{\"error\":\""+errMsg+"\"}");
////				response.setStatus(500);
//
//				ResponseUtils.responseFailed(response,errMsg);
//			}
//
//		});
//	}
//	@Override
//	public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
//		oauthServer.tokenKeyAccess("permitAll()")
//				.checkTokenAccess("permitAll()")
//			    .passwordEncoder(passwordEncoder);
//		oauthServer.allowFormAuthenticationForClients();
//	}
//
////	@Bean
////	public WebResponseExceptionTranslator webResponseExceptionTranslator() {
////		return new DefaultWebResponseExceptionTranslator() {
////			public static final String BAD_MSG = "坏的凭证";
////
////			@Override
////			public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
////				OAuth2Exception oAuth2Exception;
////				if (e.getMessage() != null && e.getMessage().equals(BAD_MSG)) {
////					oAuth2Exception = new InvalidGrantException("用户名或密码错误", e);
////				} else if (e instanceof InternalAuthenticationServiceException) {
////					oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
////				} else if (e instanceof RedirectMismatchException) {
////					oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
////				} else if (e instanceof InvalidScopeException) {
////					oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
////				} else {
////					oAuth2Exception = new UnsupportedResponseTypeException("服务内部错误", e);
////				}
////				ResponseEntity<OAuth2Exception> response = super.translate(oAuth2Exception);
////				ResponseEntity.status(oAuth2Exception.getHttpErrorCode());
////				response.getBody().addAdditionalInformation("code", oAuth2Exception.getHttpErrorCode() + "");
////				response.getBody().addAdditionalInformation("message", oAuth2Exception.getMessage());
//////				ResponseUtils.responseFailed(response,oAuth2Exception.getMessage());
////				return response;
////			}
////		};
////	}
//
//}
